package com.xiaoxing.paimai.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.xiaoxing.gifloadingview.LoadingDialogUtil;
import com.xiaoxing.paimai.R;
import com.xiaoxing.paimai.di.component.DaggerZiZhuCunQuGuiMainComponent;
import com.xiaoxing.paimai.di.module.ZiZhuCunQuGuiMainModule;
import com.xiaoxing.paimai.mvp.contract.ZiZhuCunQuGuiMainContract;
import com.xiaoxing.paimai.mvp.presenter.ZiZhuCunQuGuiMainPresenter;
import com.xiaoxing.paimai.mvp.ui.entity.InfoByQRCodeMid;
import com.xiaoxing.paimai.mvp.ui.fragment.ChuKuLieBiaoFragment;
import com.xiaoxing.paimai.mvp.ui.fragment.KuCunLieBiaoFragment;
import com.xiaoxing.paimai.mvp.ui.inter.ScanI;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.armscomponent.commonres.utils.SlidingTabLayoutUtil;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonsdk.core.BaseConstants;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;

import static com.jess.arms.utils.Preconditions.checkNotNull;
import static me.jessyan.armscomponent.commonsdk.core.BaseConstants.SCAN_REQUEST_CODE;


@Route(path = RouterHub.APP_ZI_ZHU_CUN_QU_GUI_ACTIVITY)
public class ZiZhuCunQuGuiMainActivity extends BaseActivity<ZiZhuCunQuGuiMainPresenter> implements ZiZhuCunQuGuiMainContract.View {

    private static final int STOP = 0;
    private static final int THREADING = 1;
    private static final int POSTSUCCESS = 2;
    private static final int POSTERROR = 3;
    private final String[] mTitles = {"库存列表", "出库列表"};
    List<InfoByQRCodeMid> list_InfoByQRCodeMid = null;
    @BindView(R.id.tv_kai_men)
    TextView tvKaiMem;
    private String scanResult = "";
    private String scanResultSub = "";
    private InfoByQRCodeMid infoByQRCodeMid = new InfoByQRCodeMid(this);
    private MyHandler mMyHandler;
    private ScanI mScanIKuCun;
    private ScanI mScanIChuKu;
    private String resultStr = "";


    /**
     * 用于注册回调事件
     */
    public void registerMyScanIKuCunListener(ScanI scanI) {
        this.mScanIKuCun = scanI;
    }

    public void registerMyScanIChuKuListener(ScanI scanI) {
        this.mScanIChuKu = scanI;
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerZiZhuCunQuGuiMainComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .ziZhuCunQuGuiMainModule(new ZiZhuCunQuGuiMainModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_zi_zhu_cun_qu_gui_main; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleNoBack(this, "主页");


        ArrayList<Fragment> mFragments = new ArrayList<>();
        mFragments.add(KuCunLieBiaoFragment.newInstance());
        mFragments.add(ChuKuLieBiaoFragment.newInstance());

        SlidingTabLayoutUtil.init(this, mTitles, mFragments);
        mMyHandler = new MyHandler();

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @OnClick({R.id.store_btn_QRCode, R.id.store_url_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.store_btn_QRCode:
                toCapture();
                break;

        }

    }

    private void toCapture() {
//        Intent openCameraIntent = new Intent(this, CaptureActivity.class);
//        startActivityForResult(openCameraIntent, 0);

        Intent newIntent = new Intent(this, ScanQRCodeActivity.class);
        mSharedPreferencesHelper.putInt(SCAN_REQUEST_CODE, 101);
        // 开始一个新的 Activity等候返回结果
        startActivityForResult(newIntent, 101);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == 101) {
            Bundle bundle = data.getExtras();
            scanResult = bundle.getString("scan_result");

            scanResultSub = scanResult.substring(scanResult.lastIndexOf("?") + 1, scanResult.length());


            mSharedPreferencesHelper.putString(BaseConstants.SCAN_RESULT_SUB, scanResultSub);

            String sub = scanResultSub.split("=")[0];


            //扫描之后回调获取接口数据
            if (null != mScanIKuCun) {
                String sid = scanResultSub.substring(
                        scanResultSub.lastIndexOf("=") + 1,
                        scanResultSub.length());

//                tvKaiMem.setVisibility(View.VISIBLE);
                mScanIKuCun.getKuCunOrChuKuList(sid);
                mScanIChuKu.getKuCunOrChuKuList(sid);
            }


//            if (sub.equals("sid")) {
//
//
//                new Thread() {
//                    @Override
//                    public void run() {
//
//                        int uid = Integer.parseInt(mSharedPreferencesHelper.getString(BaseConstants.UID));
//                        String LoginName = mSharedPreferencesHelper.getString(BaseConstants.USERNAME);
//                        String path = scanResult + "&uid=" + uid + "_" + LoginName;
//
//                        try {
//                            // 1.定义请求url
//                            URL url = new URL(path);
//                            // 2.建立一个http的连接
//                            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//                            // 3.设置一些请求的参数
//                            conn.setRequestMethod("POST");
//                            conn.setRequestProperty("User-Agent",
//                                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");
//                            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//                            String data1 = scanResultSub + "&uid=" + uid + "_" + LoginName;
//                            conn.setRequestProperty("Content-Length", data1.length() + "");
//                            conn.setConnectTimeout(5000);// 设置连接超时时间
//                            conn.setReadTimeout(5000); // 设置读取的超时时间
//
//                            // 4.一定要记得设置 把数据以流的方式写给服务器
//                            conn.setDoOutput(true); // 设置要向服务器写数据
//                            conn.getOutputStream().write(data1.getBytes());
//
//                            int code = conn.getResponseCode(); // 服务器的响应码
//                            // 200 OK
//                            // //404
//                            // 页面找不到
//                            if (code == 200) {
//                                Message m = new Message();
//                                m.what = THREADING;
//                                mMyHandler.sendMessage(m);
//                            }
//
//                        } catch (Exception e) {
//                            // TODO: handle exception
//
//                            String s = e.getStackTrace().toString();
//
//                            Message m = new Message();
//                            m.what = POSTERROR;
//                            mMyHandler.sendMessage(m);
//                        }
//
//                    }
//                }.start();
//
////				Intent in = new Intent(ListByQRCodeActivity.this,StoreListQRCOpenDoor.class);
////				in.putExtra("scanResult", scanResult);
////				startActivity(in);
//
//            } else {
//
//                new Thread() {
//                    @Override
//                    public void run() {
//
//                        int uid = Integer.parseInt(mSharedPreferencesHelper.getString(BaseConstants.UID));
//
//                        String spid = scanResultSub.substring(scanResultSub.lastIndexOf("=") + 1,
//                                scanResultSub.length());
//
//                        list_InfoByQRCodeMid = GetListInfoByQRCodeMidFromWebService(spid, uid, "1");
//
//                        if (list_InfoByQRCodeMid.size() > 0) {
//                            Message m = new Message();
//                            m.what = STOP;
//                            mMyHandler.sendMessage(m);
//                        } else {
//                            Message m = new Message();
//                            m.what = THREADING;
//                            mMyHandler.sendMessage(m);
//                        }
//
//                    }
//                }.start();
//            }

        }
    }


    @OnClick(R.id.tv_kai_men)
    void openTheDoor() {
        if (scanResult.length() == 0) {
            Toast.makeText(ZiZhuCunQuGuiMainActivity.this, "请先扫描二维码,再开门！！！", Toast.LENGTH_LONG).show();
            toCapture();
        } else {

            new Thread() {
                @Override
                public void run() {

                    int uid = Integer.parseInt(mSharedPreferencesHelper.getString(BaseConstants.UID));
                    String LoginName = mSharedPreferencesHelper.getString(BaseConstants.USERNAME);
                    String path = scanResult + "&uid=" + uid + "_" + LoginName;

                    try {
                        // 1.定义请求url
                        URL url = new URL(path);
                        // 2.建立一个http的连接
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        // 3.设置一些请求的参数
                        conn.setRequestMethod("POST");
                        conn.setRequestProperty("User-Agent",
                                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");
                        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                        String data = scanResultSub + "&uid=" + uid + "_" + LoginName;
                        conn.setRequestProperty("Content-Length", data.length() + "");
                        conn.setConnectTimeout(5000);// 设置连接超时时间
                        conn.setReadTimeout(5000); // 设置读取的超时时间

                        // 4.一定要记得设置 把数据以流的方式写给服务器
                        conn.setDoOutput(true); // 设置要向服务器写数据
                        conn.getOutputStream().write(data.getBytes());

                        int code = conn.getResponseCode(); // 服务器的响应码
                        // 200 OK
                        // //404
                        // 页面找不到

                        if (code == 200) {
                            // Message m = new Message();
                            // m.what =
                            // ListByQRCodeActivity.POSTSUCCESS;
                            // hanlder.sendMessage(m);

                            InputStream is = conn.getInputStream();
                            // 把is的内容转换为字符串
                            ByteArrayOutputStream bos = new ByteArrayOutputStream();
                            byte[] buffer = new byte[1024];
                            int len = -1;
                            while ((len = is.read(buffer)) != -1) {
                                bos.write(buffer, 0, len);
                            }
                            String result = new String(bos.toByteArray());

                            Pattern p1 = Pattern.compile("<span id=\"Label1\">([^<]+)</span>");
                            Matcher m1 = p1.matcher(result);
                            if (m1.find()) {
                                resultStr = m1.group(1);
                            }

                            // String test1
                            // =result.substring(result.indexOf("<span
                            // id=\"Label1\">")+1,result.lastIndexOf("</span>"));

                            Message m = new Message();
                            m.what = POSTSUCCESS;
                            mMyHandler.sendMessage(m);

                        } else {
                            Message m = new Message();
                            m.what = POSTERROR;
                            mMyHandler.sendMessage(m);
                        }

                    } catch (Exception e) {
                        String s = e.getStackTrace().toString();
                    }

                }
            }.start();
        }


    }

    // 获取基本信息
    private List<InfoByQRCodeMid> GetListInfoByQRCodeMidFromWebService(String spid, int uid, String page) {

        List<InfoByQRCodeMid> list = null;
        try {
            /****************** 调用webService ***********************/
            // 调用.net 的WebService.
            String nameSpace = "http://tempuri.org/";
            String methodName = "getMyOut";

            String url = "http://" + getSpIP() + ":" + getSpPort()
                    + "/ws/ContainerService.asmx";
            String soapAction = nameSpace + methodName;

            // 设置连接参数
            SoapObject request = new SoapObject(nameSpace, methodName);

            // 增加属性参数。 将相关的函数参数放入到过程中。
            request.addProperty("spid", spid);
            request.addProperty("uid", uid);
            request.addProperty("page", page);

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
            // V1.1）;

            // 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
            // 不指定rpc方式则用true否则要用false
            envelope.dotNet = true;

            // envelope.setOutputSoapObject(request);//设置请求参数
            envelope.bodyOut = request; // enveloper.bodyOut=request 与
            // envelope.setOutputSoapObject(request)
            // 效果相同。
            // step4 创建HttpTransportSE对象
            HttpTransportSE ht = new HttpTransportSE(url);
            // step5 调用WebService
            ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
            if (envelope.getResponse() != null) {
                SoapPrimitive response = (SoapPrimitive) envelope.getResponse();

                String returnStr = response.toString();

                if ("" != returnStr) {
                    returnStr = returnStr.substring(returnStr.lastIndexOf("["), returnStr.length());

                    returnStr = returnStr.replace("\\", "");

                    list = infoByQRCodeMid.getListFromJSON(returnStr);

                }

            }
            /****************** 调用webService结束 ***********************/

        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }

    private String getSpIP() {
        return mSharedPreferencesHelper.getString(BaseConstants.SHE_ZHI_IP);
    }

    private String getSpPort() {
        return mSharedPreferencesHelper.getString(BaseConstants.SHE_ZHI_PORT);
    }

    class MyHandler extends Handler {
        public MyHandler() {
        }

        public MyHandler(Looper L) {
            super(L);
        }

        // 子类必须重写此方法，接受数据
        @Override
        public void handleMessage(Message msg) {
            LoadingDialogUtil.dismissDialog();
            switch (msg.what) {
                case THREADING:
                    break;

                case STOP:
                    break;
                case 4:

                    break;
                case 6:
                    break;
                case 7:
                    break;
                case 8:
                    break;

                case POSTSUCCESS:
                    ArmsUtils.makeText(ZiZhuCunQuGuiMainActivity.this, resultStr);

                    break;
                case POSTERROR:
                    ArmsUtils.makeText(ZiZhuCunQuGuiMainActivity.this, "开门失败");
                    break;
                default:
                    break;
            }
        }


    }
}
